package sample.com.wisdomhealth.ui;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PersistableBundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hyg.lib_base.lisener.AppUpdateListener;
import com.hyg.lib_base.mainUtils.BluetoothUtils;
import com.hyg.lib_base.mainUtils.StatusBarUtil;
import com.hyg.lib_base.mainUtils.Utils;
import com.hyg.lib_common.Base.BaseActivity;
import com.hyg.lib_common.DataModel.EventBusMessage;
import com.hyg.lib_common.DataModel.personal.UserDetail;
import com.hyg.lib_common.DataUtil.UserSPUtils;
import com.hyg.lib_common.Litepal.DataBaseHelper;
import com.hyg.lib_common.Litepal.DataBaseUpdateLisenner;
import com.hyg.lib_common.constant.UrlUtils;
import com.hyg.lib_common.ThirdSDK.PuGongYing;
import com.hyg.lib_common.constant.Constants;
import com.hyg.lib_common.constant.FileConstants;
import com.hyg.lib_common.listener.LoginStateListener;
import com.hyg.lib_common.loginpart.LoginFasterActivity;
import com.hyg.lib_common.loginpart.LoginFasterUtil;
import com.hyg.lib_common.sweetalertdialog.MyDialog;
import com.hyg.module_health.view.fragment.HealthFragment;
import com.hyg.module_testing.ui.fragment.TestingFragment;
import com.hyg.module_testing.ui.fragment.TestingSelfFragment;
import com.hyg.module_user.ui.UserFragment;


import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import okhttp3.FormBody;
import sample.com.wisdomhealth.R;
import sample.com.wisdomhealth.adapter.MyFragmentAdapter;

/**
 * description: 项目主页
 *
 * @author visitant
 * @time 2020/11/30 9:55
 */
@Route(path = Constants.PATH_ACTIVITY_MAIN)
public class MainActivity extends BaseActivity implements View.OnClickListener {
    public ImageView iv1, iv2, iv4;
    public TextView tv_text1, tv_text2, tv_text4;
    public ViewPager mViewPager;
    HealthFragment healthFragment;
    TestingFragment testingFragment;
    UserFragment userFragment;
//    TestingSelfFragment testingFragment;
    public long touchTime = 0;
    public MyHandler myHandler;
    ProgressBar progressBar;
    BluetoothUtils bluetoothUtils;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        if (savedInstanceState != null) {
//            String FRAGMENTS_TAG = "android:support:fragments";
//            savedInstanceState.remove(FRAGMENTS_TAG);
//        }
        if(savedInstanceState!= null)
        {
            String FRAGMENTS_TAG ="android:support:fragments";
            savedInstanceState.remove(FRAGMENTS_TAG);
        }

        setContentView(R.layout.activity_main);
        init();
    }

    /**
     * description: 初始化
     *
     * @author visitant
     * @time 2020/11/30 13:38
     */
    public void init() {
        initView();
        initData();
    }


    /**
     * description: 初始化view
     *
     * @author visitant
     * @time 2020/11/30 11:36
     */
    public void initView() {
//        getWindow().setBackgroundDrawable(getResources().getDrawable(com.hyg.lib_common.R.drawable.window_background));
        StatusBarUtil.setStatusBar(3, this, getResources().getColor(R.color.white), 10, null, null, true);
        tv_text1 = (TextView) findViewById(R.id.text1);
        tv_text2 = (TextView) findViewById(R.id.text2);
        tv_text4 = (TextView) findViewById(R.id.text4);
        iv1 = (ImageView) findViewById(R.id.iv1);
        iv2 = (ImageView) findViewById(R.id.iv2);
        iv4 = (ImageView) findViewById(R.id.iv4);
        tv_text1.setOnClickListener(this); // 设置页面1标签的点击事件
        tv_text2.setOnClickListener(this); // 设置页面2标签的点击事件
        tv_text4.setOnClickListener(this); // 设置页面3标签的点击事件
        iv1.setOnClickListener(this);
        iv2.setOnClickListener(this);
        iv4.setOnClickListener(this);
        initViewpager();
    }

    public void initData() {
        myHandler = new MyHandler(this);
        PackageManager pm = getPackageManager();
//        initDataBase();
    }




    /**
     * description: 初始化viewpager
     *
     * @author visitant
     * @time 2020/11/30 11:36
     */
    public void initViewpager() {
        mViewPager = (ViewPager) findViewById(R.id.ViewPager1);// 定义页面设置成带有动画和滑动效果的mViewpager对象
        List<Fragment> mList = new ArrayList<Fragment>(); // 创建一个List，用于存放4个页面
        healthFragment = new HealthFragment();
//        testingFragment = new TestingSelfFragment();
        testingFragment = new TestingFragment();
        userFragment = new UserFragment();
        mList.add(healthFragment);
        mList.add(testingFragment);
        mList.add(userFragment);
        MyFragmentAdapter adapter = new MyFragmentAdapter(getSupportFragmentManager(), (ArrayList<Fragment>) mList);
        mViewPager.addOnPageChangeListener(initListener());
        mViewPager.setAdapter(adapter); // 将adapter设置为mViewPager的adapter
        mViewPager.setOffscreenPageLimit(2); //viewpager 的预加载页面 太少时会销毁重建
    }

    /**
     * description:  滑动监听
     *
     * @return ViewPager 的滑动监听器
     * @author visitant
     * @time 2020/11/30 11:32
     */
    public ViewPager.OnPageChangeListener initListener() {
        ViewPager.OnPageChangeListener listener = new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                switch (position) {
                    case 0:// 将页面1设置成白色
                        tv_text1.setTextColor(getResources().getColor(R.color.MainThemeColor));
                        tv_text2.setTextColor(getResources().getColor(R.color.text_deep));
                        tv_text4.setTextColor(getResources().getColor(R.color.text_deep));
                        iv1.setImageResource(R.mipmap.frist_type_c);
                        iv2.setImageResource(R.mipmap.self_examination);
                        iv4.setImageResource(R.mipmap.my_setup);
                        break;
                    case 1:// 将页面2设置成白色
                        tv_text1.setTextColor(getResources().getColor(R.color.text_deep));
                        tv_text2.setTextColor(getResources().getColor(R.color.MainThemeColor));
                        tv_text4.setTextColor(getResources().getColor(R.color.text_deep));
                        iv1.setImageResource(R.mipmap.frist_type);
                        iv2.setImageResource(R.mipmap.self_examination_c);
                        iv4.setImageResource(R.mipmap.my_setup);
                        break;
                    case 2:
                        tv_text1.setTextColor(getResources().getColor(R.color.text_deep));
                        tv_text2.setTextColor(getResources().getColor(R.color.text_deep));
                        tv_text4.setTextColor(getResources().getColor(R.color.MainThemeColor));
                        iv1.setImageResource(R.mipmap.frist_type);
                        iv2.setImageResource(R.mipmap.self_examination);
                        iv4.setImageResource(R.mipmap.my_setup_c);
                        break;
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        };
        return listener;
    }

    /**
     * description: 初始化问卷题目
     *
     * @author visitant
     * @time 2021/1/20 17:32
     */
    public void initDataBase() {
        DataBaseHelper dataBaseHelper = new DataBaseHelper(this);
        if (dataBaseHelper.checkVersion()) {
            dataBaseHelper.updateDataBase(new DataBaseUpdateLisenner() {
                @Override
                public void onStart() {
                    Log.i(TAG, "onStart: dataBaseHelper");
                }

                @Override
                public void onSuccess() {
                    Log.i(TAG, "onSuccess: dataBaseHelper");
                }

                @Override
                public void onFail(String errorFileName) {
                    Log.i(TAG, "onFail: " + errorFileName);
                }
            });
        }
    }


    @Override
    public void onClick(View v) {
        int index = 0;
        switch (v.getId()) {
            case R.id.text1:
                index = 0;
                break;
            case R.id.text2:
                index = 1;
                break;
            case R.id.text4:
                index = 2;
                break;
            case R.id.iv1:
                index = 0;
                break;
            case R.id.iv2:
                index = 1;
                break;
            case R.id.iv4:
                index = 2;
                break;
        }
        mViewPager.setCurrentItem(index); // 设置当前显示的页面
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (!Utils.isEmpty(sn.getString("phone", "")) && !Utils.isEmpty(sn.getString("token", ""))) {
            getUserInfo();// 是否需要刷新数据
            getUserLevelInfo();//查询 用户使用医疗版还是 商务版的标识
        }
    }

    /**
     * description:   获取用户详细信息
     *
     * @author visitant
     * @time 2020/12/8 11:26
     */
    public void getUserInfo() {
        Log.i("lgb", "getUserInfo=====: "+sn.getString("token", ""));
        String str_tag = "1";
        FormBody formBody = new FormBody.Builder()
                .add("token", sn.getString("token", ""))//设置参数名称和参数值
                .build();
        sendPostNetwork(str_tag, formBody, myHandler, UrlUtils.getUserInfoAddr);
    }

    /**
     * description: 获取用户等级信息
     *
     * @author visitant
     * @time 2020/12/8 11:27
     */
    public void getUserLevelInfo() {
        String str_tag = "3";
        FormBody formBody = new FormBody.Builder()
                .add("token", sn.getString("token", ""))//设置参数名称和参数值
                .build();
        sendPostNetwork(str_tag, formBody, myHandler, UrlUtils.getUserLevelAddr);
    }


    public class MyHandler extends Handler {
        public final WeakReference<Context> reference;
        public MainActivity activity;

        public MyHandler(Context context) {
            reference = new WeakReference<>(context);
            activity = (MainActivity) reference.get();
        }

        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1://获取用户详细信息并保存
                    JSONObject jsondata = JSON.parseObject(msg.obj.toString());//获取返回的JSONObject原对象
                    String status = jsondata.getString("code");
                    String message = jsondata.getString("message");
                    if (status.equals("200")) {
                        UserSPUtils.putUserString(MainActivity.this, FileConstants.UserDetailData, jsondata.getString("data"));
                        UserDetail userDetail = JSONObject.parseObject(jsondata.getString("data"), UserDetail.class);
                        userFragment.updateImage(userDetail);
                    } else {
                        Log.i("lgb", "handleMessage:main 111");
                        activity.ErrorDialog(message);
                    }
                    break;
                case 3://查询商务版 || 医疗版体质 展示形式
                    JSONObject jsondata1 = JSON.parseObject(msg.obj.toString());//获取返回的JSONObject原对象
                    if (jsondata1.getString("code").equals("200")) {
                        if (!Utils.isEmpty(jsondata1.getString("data"))) {
                            JSONArray data = JSONArray.parseArray(jsondata1.getString("data"));
                            if (0 < data.size())
                                for (int i = 0; i < data.size(); i++) {
                                    JSONObject datas = (JSONObject) data.get(i);
                                    if (!Utils.isEmpty(datas.getString("termName")) && datas.getString("termName").equals("tizhi")) {
                                        activity.editorn = activity.sn.edit();
                                        activity.editorn.putString("PackageSelection", Utils.isEmpty(datas.getString("value")) ? "2" : datas.getString("value"));
                                        activity.editorn.commit();
                                    }
                                }
                        }
                    } else {
                        Log.d(ErrorTAG, "" + jsondata1.getString("message"));
                    }
                    break;
            }
        }
    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Bundle bundle = intent.getBundleExtra("bundle");
        if (bundle != null) {
            boolean mIsExit = bundle.getBoolean(Constants.TAG_EXIT, false);
            if (mIsExit) {
                this.finish();
            } else {
                mViewPager.setCurrentItem(0);
            }
        }
    }

    @Override
    public void onBackPressed() {
        long time = System.currentTimeMillis();
        if (time - touchTime > 2000) {
            Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            touchTime = time;
        } else {
//            EventBus.getDefault().post(new EventBusMessage("finishAllActivity"));
            finish();
//            finishAffinity();
        }
    }

//    @Subscribe
//    public void onEvent(EventBusMessage message) {
//        //接收以及处理数据
//        if(message.getmessage().equals("finishAllActivity")){
//            finish();
//        }
//    }


//    @Override
//    public void finish() {
//        super.finish();
//        finishAffinity();
//    }


    @Override
    public void onSaveInstanceState(@NonNull Bundle outState, @NonNull PersistableBundle outPersistentState) {
//        super.onSaveInstanceState(outState, outPersistentState);



    }
}